# quick-research-web.py
from flask import Flask, render_template_string, request, redirect, url_for, jsonify
import os
import json
from subsystem_manager import SubsystemCreator, SubsystemDeleter

# 切换到当前脚本所在的目录
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)

app = Flask(__name__)
DATA_FILE = 'data.json'

# 加载JSON数据
def load_data():
    if os.path.exists(DATA_FILE):
        with open(DATA_FILE, 'r', encoding='utf-8') as file:
            return json.load(file)
    return {'users': [], 'subsystems': [], 'config': {}, 'allowed_images': []}

# 保存JSON数据
def save_data(data):
    with open(DATA_FILE, 'w', encoding='utf-8') as file:
        json.dump(data, file, indent=4, ensure_ascii=False)

@app.route('/')
def index():
    data = load_data()
    config = data.get('config', {})
    allowed_images = data.get('allowed_images', [])
    return render_template_string(TEMPLATE, subsystems=data['subsystems'], image_list=allowed_images, config=config, allowed_images=allowed_images)

@app.route('/set_config', methods=['POST'])
def set_config():
    server_ip = request.form['server_ip']
    subsystem_username = request.form['subsystem_username']
    subsystem_password = request.form['subsystem_password']

    data = load_data()
    data['config'] = {
        'server_ip': server_ip,
        'subsystem_username': subsystem_username,
        'subsystem_password': subsystem_password
    }
    save_data(data)

    return redirect(url_for('index'))

@app.route('/set_allowed_images', methods=['POST'])
def set_allowed_images():
    images = request.form['allowed_images'].splitlines()

    data = load_data()
    data['allowed_images'] = [img.strip() for img in images if img.strip()]
    save_data(data)

    return redirect(url_for('index'))

@app.route('/create_subsystem', methods=['POST'])
def create_subsystem():
    username = request.form['username']
    image = request.form['image']
    port1 = int(request.form['port1'])
    port2 = int(request.form['port2'])
    custom_params = request.form['custom_params']  # 接收自定义参数

    data = load_data()
    config = data.get('config', {})

    creator = SubsystemCreator(config['server_ip'], data['allowed_images'])
    try:
        creator.create_subsystem(username, image, port1, port2, config['subsystem_username'], config['subsystem_password'], custom_params)
        data['subsystems'].append({
            'username': username,
            'image': image,
            'port1': port1,
            'port2': port2
        })
        save_data(data)
        return jsonify(success=True)
    except Exception as e:
        return jsonify(success=False, error=str(e))

@app.route('/delete_subsystem', methods=['POST'])
def delete_subsystem():
    container_name = request.form['container_name']

    data = load_data()
    subsystems = data.get('subsystems', [])
    
    subsystem = next((s for s in subsystems if "{}-{}-{}".format(s['username'], s['image'], s['port1']) == container_name), None)
    if subsystem is None:
        return jsonify(success=False, error="容器 {} 未找到".format(container_name))
    
    username = subsystem['username']
    image_name = subsystem['image']
    port1 = subsystem['port1']
    
    deleter = SubsystemDeleter()

    try:
        deleter.delete_subsystem(username, image_name, port1)
        data['subsystems'] = [s for s in subsystems if "{}-{}-{}".format(s['username'], s['image'], s['port1']) != container_name]
        save_data(data)
        return jsonify(success=True)
    except Exception as e:
        return jsonify(success=False, error=str(e))

TEMPLATE = """
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>QuickResearch 后台管理</title>
    <link href="static/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .centered {
            text-align: center;
        }
    </style>
    <script>
        function handleFormSubmit(event, form, errorMessage) {
            event.preventDefault();
            showLoadingModal();
            const formData = new FormData(form);
            fetch(form.action, {
                method: form.method,
                body: formData,
            })
            .then(response => response.json())
            .then(data => {
                hideLoadingModal();
                if (data.success) {
                    window.location.reload();
                } else {
                    alert(errorMessage + ": " + data.error);
                }
            })
            .catch(error => {
                hideLoadingModal();
                alert(errorMessage + ": " + error);
            });
        }

        function confirmDelete(event, form, subsystemName) {
            event.preventDefault();
            const confirmation = prompt("请输入“确认删除”以确认删除操作：" + subsystemName);
            if (confirmation === "确认删除") {
                handleFormSubmit(event, form, "子系统删除失败");
            } else {
                alert("删除操作已取消。");
            }
        }

        function showLoadingModal() {
            document.getElementById('loadingModal').style.display = 'block';
        }

        function hideLoadingModal() {
            document.getElementById('loadingModal').style.display = 'none';
        }
    </script>
</head>
<body>
    <div class="container">
        <h1 class="centered">QuickResearch 后台管理</h1>

        <!-- 设置全局配置表单 -->
        <form action="/set_config" method="POST">
            <div class="form-group">
                <label for="server_ip">服务器 IP</label>
                <input type="text" class="form-control" id="server_ip" name="server_ip" value="{{ config.server_ip }}" required>
            </div>
            <div class="form-group">
                <label for="subsystem_username">子系统用户名</label>
                <input type="text" class="form-control" id="subsystem_username" name="subsystem_username" value="{{ config.subsystem_username }}" required>
            </div>
            <div class="form-group">
                <label for="subsystem_password">子系统登录密码</label>
                <input type="text" class="form-control" id="subsystem_password" name="subsystem_password" value="{{ config.subsystem_password }}" required>
            </div>
            <button type="submit" class="btn btn-primary">保存配置</button>
        </form>
        
        <hr>
        
        <!-- 设置允许的镜像列表表单 -->
        <form action="/set_allowed_images" method="POST">
            <div class="form-group">
                <label for="allowed_images">允许的镜像列表</label>
                <textarea class="form-control" id="allowed_images" name="allowed_images" rows="10">{{ allowed_images | join('\n') }}</textarea>
            </div>
            <button type="submit" class="btn btn-primary">保存镜像列表</button>
        </form>

        <hr>
        
        <!-- 创建子系统表单 -->
        <form action="/create_subsystem" method="POST" onsubmit="handleFormSubmit(event, this, '子系统创建失败')">
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" class="form-control" id="username" name="username" required>
            </div>
            <div class="form-group">
                <label for="image">镜像名</label>
                <select class="form-control" id="image" name="image" required>
                    {% for image in allowed_images %}
                        <option value="{{ image }}">{{ image }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="form-group">
                <label for="port1">端口1</label>
                <input type="number" class="form-control" id="port1" name="port1" required>
            </div>
            <div class="form-group">
                <label for="port2">端口2</label>
                <input type="number" class="form-control" id="port2" name="port2" required>
            </div>
            <div class="form-group">
                <label for="custom_params">自定义参数</label>
                <input type="text" class="form-control" id="custom_params" name="custom_params">
            </div>
            <button type="submit" class="btn btn-primary">创建子系统</button>
        </form>
        
        <hr>
        
        <!-- 显示子系统信息 -->
        <h2>子系统列表</h2>
        <table class="table">
            <thead>
                <tr>
                    <th>用户名</th>
                    <th>镜像名</th>
                    <th>端口1</th>
                    <th>端口2</th>
                    <th>远程桌面地址</th>
                    <th>远程IDE地址</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for subsystem in subsystems %}
                    <tr>
                        <td>{{ subsystem.username }}</td>
                        <td>{{ subsystem.image }}</td>
                        <td>{{ subsystem.port1 }}</td>
                        <td>{{ subsystem.port2 }}</td>
                        <td>http://{{ config.server_ip }}:{{ subsystem.port1 }}</td>
                        <td>https://{{ config.server_ip }}:{{ subsystem.port2 }}</td>
                        <td>
                            <form action="/delete_subsystem" method="POST" onsubmit="confirmDelete(event, this, '{{ subsystem.username }}-{{ subsystem.image }}-{{ subsystem.port1 }}')" style="display:inline;">
                                <input type="hidden" name="container_name" value="{{ subsystem.username }}-{{ subsystem.image }}-{{ subsystem.port1 }}">
                                <button type="submit" class="btn btn-danger">删除</button>
                            </form>
                        </td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

    <!-- Loading Modal -->
    <div id="loadingModal" class="modal" tabindex="-1" role="dialog" style="display:none;">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">请稍候...</h5>
                </div>
                <div class="modal-body">
                    <p>操作正在进行中，请稍候。</p>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
"""

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9003, debug=False)
